﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Annual_faculty_promotions.Core.Domain;
using Annual_faculty_promotions.Core.Enums;
using Annual_faculty_promotions.Data;
using Annual_faculty_promotions.Service.Contracts;
using Annual_faculty_promotions.WebUI.Areas.UserArea.Models;
using Annual_faculty_promotions.WebUI.Helpers;
using Annual_faculty_promotions.WebUI.Helpers.Filters;
using Microsoft.AspNet.Identity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


namespace Annual_faculty_promotions.WebUI.Areas.UserArea.Controllers
{
    [Authorize]
    public class RequestController : Controller
    {
        private readonly IUnivercityStructureService _univercityStructureService;
        private readonly IRequestService _requestService;
        private readonly IArchiveService _archiveService;
        private readonly IUnitOfWork _unitOfWork;

        public RequestController(IUnivercityStructureService univercityStructure,
            IUnitOfWork unitOfWork,
            IRequestService requestService,
            IArchiveService archiveService)
        {
            _unitOfWork = unitOfWork;
            _univercityStructureService = univercityStructure;
            _requestService = requestService;
            _archiveService = archiveService;
        }



        public ActionResult Index()
        {
            System.Globalization.PersianCalendar d = new System.Globalization.PersianCalendar();

            int uId = int.Parse(User.Identity.GetUserId());
            var archive = _archiveService
                .Where(x => x.User.Id == uId).ToList().LastOrDefault();

            ViewBag.LastDateGrade = archive == null ? "بدون مقدار" : d.ToDateTime(archive.CreatedDate.Year, archive.CreatedDate.Month, archive.CreatedDate.Day, 0, 0, 0, 0, 0).ToString();


            //  var req = System.Web.Helpers.Json.Encode(_requestService.Where(r => r.Term == DateTime.Now.Year).Include(r => r.EducationalResearches));
            var model = new AddRequestViewModel();
            var _term = d.GetYear(DateTime.Now);
            model.Request = _requestService.Where(x => x.Term == _term && x.UserId == uId).Include(x => x.UnivercityStructure).FirstOrDefault();
            model.UnivercityStructures = _univercityStructureService.Where(x => x.HasChild == false && x.Level == 3).ToList();
            if (model.Request != null)
            {
                var md = _requestService.Where(x=>x.RequestId==model.Request.Id).ToList().FirstOrDefault();
                if (md == null)
                    model.FurtherInformation = new FurtherInformation();
                else
                    model.FurtherInformation = md;
            }
            ViewBag.Department =
                new SelectList(_univercityStructureService.Where(x => x.HasChild == false && x.Level == 3), "Id", "Name", model.Request != null ? model.Request.UnivercityStructureId : 0);

            return View(model);
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult Create(Request request)
        {
            if (ModelState.IsValid)
            {
                var req = new Request();
                PersianCalendar pc = new PersianCalendar();
                req = request;
                req.UserId = int.Parse(User.Identity.GetUserId());

                req.Term = pc.GetYear(DateTime.Now);
                req.Status = RequestStatus.درجریان;

                if (request.Id == 0)
                    _requestService.AddNewRequest(req);
                else
                {
                    _requestService.EditRequest(req);
                }


                _unitOfWork.SaveChanges();


                return Json(new { Success = true, Msg = "ثبت شد" });
            }
            return Json(new { Success = false, Msg = "خطا در ثبت!" });


        }


        public ActionResult GetEducation(long requestid)
        {
            var data = _requestService.GetEducation_ByRequestId_ForCurrentYear(requestid).ToList();
            JArray ja = new JArray();

            foreach (var item in data)
            {
                var itemObject = new JObject
                    {
                        {"Id",item.Id},
                        {"EducationalResearchStatus",((EducationalResearchStatus)item.EducationalResearchStatus).ToString()},
                        {"Term",((Term)item.Term).ToString().Replace("_"," ")},
                        {"Subject",item.Subject},
                        {"CourseNo",item.CourseNo},
                        {"UnitCount",item.UnitCount },
                        {"GradeEducation", item.GradeEducation.ToString()},
                        {"StudentCount",item.StudentCount}
                    };
                ja.Add(itemObject);
            }

            JObject jo = new JObject();
            jo.Add("total", _requestService.GetEducation_ByRequestId_ForCurrentYear(requestid).Count());
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }


        public ActionResult GetResearch(long requestid)
        {
            var data = _requestService.GetReasearch_ByRequestId_ForCurrentYear(requestid).ToList();
            JArray ja = new JArray();

            foreach (var item in data)
            {
                var itemObject = new JObject
                    {
                        {"Id",item.Id},
                        {"EducationalResearchStatus",((EducationalResearchStatus)item.EducationalResearchStatus).ToString()},
                        {"Subject",item.Subject},
                        {"Term",((Term)item.Term).ToString().Replace("_"," ")},
                        {"ResearchPost",((PostPlan)item.ResearchPost).ToString()},
                        {"BeginDate",item.BeginDate},
                        {"EndDate",item.EndDate },
                        {"StudentCount",item.StudentCount}
                    };
                ja.Add(itemObject);
            }

            JObject jo = new JObject();
            jo.Add("total", _requestService.GetEducation_ByRequestId_ForCurrentYear(requestid).Count());
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }

        public ActionResult GetEducationalResearchStatus()
        {
            var items = Enum.GetValues(typeof(EducationalResearchStatus));
            JArray ja = new JArray();
            foreach (var item in items)
            {
                var itemObject = new JObject
                {
                    {"EducationalResearchStatusId", ((int)((EducationalResearchStatus)Enum.Parse(typeof(EducationalResearchStatus), item.ToString()))).ToString()},
                    {"EducationalResearchStatus",item.ToString()}
                };
                ja.Add(itemObject);
            }
            return Content(JsonConvert.SerializeObject(ja), "application/json");
        }

        public ActionResult GetPostPlan()
        {
            var items = Enum.GetValues(typeof(PostPlan));
            JArray ja = new JArray();
            foreach (var item in items)
            {
                var itemObject = new JObject
                {
                    {"PostPlanId", ((int)((PostPlan)Enum.Parse(typeof(PostPlan), item.ToString()))).ToString()},
                    {"PostPlan",item.ToString()}
                };
                ja.Add(itemObject);
            }
            return Content(JsonConvert.SerializeObject(ja), "application/json");
        }

        public ActionResult GetTerm()
        {
            var items = Enum.GetValues(typeof(Term));
            JArray ja = new JArray();
            foreach (var item in items)
            {
                var itemObject = new JObject
                {
                     {"TermId", ((int)((Term)Enum.Parse(typeof(Term), item.ToString()))).ToString()},
                    {"Term",item.ToString().Replace("_"," ")}
                };
                ja.Add(itemObject);
            }
            return Content(JsonConvert.SerializeObject(ja), "application/json");
        }

        public ActionResult GetGradeEducation()
        {
            var items = Enum.GetValues(typeof(GradeEducation));
            JArray ja = new JArray();
            foreach (var item in items)
            {
                var itemObject = new JObject
                {
                     {"GradeEducationId", ((int)((GradeEducation)Enum.Parse(typeof(GradeEducation), item.ToString()))).ToString()},
                    {"GradeEducation",item.ToString().Replace("_"," ")}
                };
                ja.Add(itemObject);
            }
            return Content(JsonConvert.SerializeObject(ja), "application/json");
        }

        public ActionResult GetTechnologyType()
        {
            var items = Enum.GetValues(typeof(TechnologyType));
            JArray ja = new JArray();
            foreach (var item in items)
            {
                var itemObject = new JObject
                {
                     {"TechnologyTypeId", ((int)((TechnologyType)Enum.Parse(typeof(TechnologyType), item.ToString()))).ToString()},
                    {"TechnologyType",item.ToString().Replace("_"," ")}
                };
                ja.Add(itemObject);
            }
            return Content(JsonConvert.SerializeObject(ja), "application/json");
        }



        public ActionResult CreateEducationReasearch(EducationalResearch educationalResearch)
        {
            if (ModelState.IsValid)
            {
                _requestService.AddEducationReasearch(educationalResearch);
                _unitOfWork.SaveChanges();
                return Json(new { Success = true, Msg = "ثبت شد" });
            }
            return Json(new { Success = false, Msg = "خطا در ثبت!" });
        }

        public ActionResult CreateDissertation(Dissertation dissertation)
        {
            if (ModelState.IsValid)
            {
                _requestService.AddDissertation(dissertation);
                _unitOfWork.SaveChanges();
                return Json(new { Success = true, Msg = "ثبت شد" });
            }
            return Json(new { Success = false, Msg = "خطا در ثبت!" });
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteEducationReasearch(int id)
        {
            try
            {
                var model = _requestService.FindEducationResearch(id);
                if (model == null)
                    return HttpNotFound();
                _requestService.DeleteEducationReasearch(id);
                _unitOfWork.SaveChanges();
                return Json(new { success = true, Msg = "حذف شد" });
            }
            catch (Exception)
            {

                return Json(new { success = false, Msg = "حذف نشد" });
            }
        }



        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteDissertation(int id)
        {
            try
            {
                var model = _requestService.FindDissertation(id);
                if (model == null)
                    return HttpNotFound();
                _requestService.DeleteDissertation(id);
                _unitOfWork.SaveChanges();
                return Json(new { success = true, Msg = "حذف شد" });
            }
            catch (Exception)
            {

                return Json(new { success = false, Msg = "حذف نشد" });
            }
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteScientificExecutive(int id)
        {
            try
            {
                var model = _requestService.FindScientificExecutive(id);
                if (model == null)
                    return HttpNotFound();
                _requestService.DeleteScientificExecutive(id);
                _unitOfWork.SaveChanges();
                return Json(new { success = true, Msg = "حذف شد" });
            }
            catch (Exception)
            {

                return Json(new { success = false, Msg = "حذف نشد" });
            }
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteTechnology(long id)
        {
            try
            {
                var model = _requestService.FindTechnology(id);
                if (model == null)
                    return HttpNotFound();
                _requestService.DeleteTechnology(id);
                _unitOfWork.SaveChanges();
                return Json(new { success = true, Msg = "حذف شد" });
            }
            catch (Exception)
            {

                return Json(new { success = false, Msg = "حذف نشد" });
            }
        }

        public ActionResult GetScientificExecutive(long requestid)
        {
            var data = _requestService.GetScientificExecutive_ByRequestId_ForCurrentYear(requestid).ToList();
            JArray ja = new JArray();

            foreach (var item in data)
            {
                var itemObject = new JObject
                    {
                        {"Id",item.Id},                
                        {"Subject",item.Subject},
                        {"LengthOfService",item.LengthOfService},
                        {"TimeHalfYear",item.TimeHalfYear},
                        {"Score",item.Score}
                    };
                ja.Add(itemObject);
            }

            JObject jo = new JObject();
            jo.Add("total", _requestService.GetEducation_ByRequestId_ForCurrentYear(requestid).Count());
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }


        public ActionResult CreateScientificExecutive(ScientificExecutive scientificExecutive)
        {
            if (ModelState.IsValid)
            {
                _requestService.AddScientificExecutive(scientificExecutive);
                _unitOfWork.SaveChanges();
                return Json(new { Success = true, Msg = "ثبت شد" });
            }
            return Json(new { Success = false, Msg = "خطا در ثبت!" });
        }

        public ActionResult CreateTechnology(Technology technology)
        {
            if (ModelState.IsValid)
            {
                _requestService.AddTechnology(technology);
                _unitOfWork.SaveChanges();
                return Json(new { Success = true, Msg = "ثبت شد" });
            }
            return Json(new { Success = false, Msg = "خطا در ثبت!" });
        }

        [HttpGet]
        [AjaxOnly]
        public ActionResult UploadAttachReasearch(int reaserchId)
        {
            var model = _requestService.FindEducationResearch(reaserchId);
            return PartialView("_AttachReaserch", model);
        }


        [HttpPost]
        public ActionResult UploadAttachReasearch(int? chunk, string name, int reaserchId)
        {
            var fileUpload = Request.Files[0];
            var uploadPath = Server.MapPath("~/App_Data/Attachments/Reaserch");
            chunk = chunk ?? 0;
            using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
            {
                if (fileUpload != null)
                {
                    var buffer = new byte[fileUpload.InputStream.Length];
                    fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, buffer.Length);
                    var model = new AttachmentResearch
                    {
                        EducationaResearchId = reaserchId,
                        FileName = name
                    };

                    _requestService.AddAttachmentResearch(model);
                }
                _unitOfWork.SaveChanges();
            }
            return Content("chunk uploaded", "text/plain");
        }


        public ActionResult ListReaserchAttachForm(int researchId)
        {
            var model = _requestService.FindEducationResearch(researchId);
            return PartialView("_listReaserchAttach", model);
        }

        public ActionResult GetReaserchAttach(int researchId)
        {
            var data = _requestService.GetAttachmentResearches(researchId).ToList();
            JArray ja = new JArray();

            foreach (var item in data)
            {
                var itemObject = new JObject
                    {
                        {"Id",item.Id},
                        {"EducationaResearchId",item.EducationaResearchId},
                        {"FileName",item.FileName}
                    };
                ja.Add(itemObject);
            }

            JObject jo = new JObject();
            jo.Add("total", _requestService.GetEducation_ByRequestId_ForCurrentYear(researchId).Count());
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }


        public ActionResult GetDissertation(int requestId)
        {
            var data = _requestService.GetDissertation_ByRequestId_ForCurrentYear(requestId).ToList();
            JArray ja = new JArray();

            foreach (var item in data)
            {
                var itemObject = new JObject
                    {
                        {"Id",item.Id},
                        {"Subject",item.Subject},
                        {"StudentName",item.StudentName},
                        {"GradeEducation",((GradeEducation)item.GradeEducation).ToString().Replace("_","")},
                        {"BeginDate",item.BeginDate},
                        {"VindicationDate",item.VindicationDate },
                        {"UnitCount",item.UnitCount },
                    };
                ja.Add(itemObject);
            }

            JObject jo = new JObject();
            jo.Add("total", _requestService.GetEducation_ByRequestId_ForCurrentYear(requestId).Count());
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }

        public ActionResult GetTechnologies(int requestId)
        {
            var data = _requestService.GetTechnology_ByRequestId_ForCurrentYear(requestId).ToList();
            JArray ja = new JArray();

            foreach (var item in data)
            {
                var itemObject = new JObject
                    {
                        {"Id",item.Id},
                        {"TechnologyType",((TechnologyType)item.TechnologyType).ToString().Replace("_","")},
                        {"Subject",item.Subject},
                        {"PresentationDate",item.PresentationDate},
                        {"PlacePresentation",item.PlacePresentation},
                        {"PartnersNames",item.PartnersNames}
                    };
                ja.Add(itemObject);
            }

            JObject jo = new JObject();
            jo.Add("total", _requestService.GetEducation_ByRequestId_ForCurrentYear(requestId).Count());
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }

        public ActionResult CreateFurtherInformation(FurtherInformation furtherInformation,
            IEnumerable<HttpPostedFileBase> officersStudyPhDUpload,
            IEnumerable<HttpPostedFileBase> typeOfPartTimeButEmployeesOtherUniversityUpload,
            IEnumerable<HttpPostedFileBase> typeOfFullTimeButRetiredUpload,
            IEnumerable<HttpPostedFileBase> typeOfFullTimeButNoRetired,
            IEnumerable<HttpPostedFileBase> passPhDPassaUpload,
            IEnumerable<HttpPostedFileBase> takingSabbaticalUpload)
        {
            if (ModelState.IsValid)
            {
                var entity = _requestService.FindFurtherInformation(furtherInformation.Id);
                if (entity == null)
                    _requestService.AddFurtherInformation(furtherInformation);
                else
                    _requestService.EditFurtherInformation(furtherInformation);
                var path = Server.MapPath("~/App_Data/FurtherInformation/" + User.Identity.Name);
               
                bool exist = System.IO.File.Exists(path);
                if (!exist)
                    System.IO.Directory.CreateDirectory(path);
                path += "/";
                // ثبت پیوست های مربوطه
                if (officersStudyPhDUpload != null)
                {
                    foreach (var item in officersStudyPhDUpload)
                    {
                        string temppath = path + Guid.NewGuid().ToString() + Path.GetExtension(item.FileName);
                        item.InputStream.ResizeImageByWidth(500, temppath, Utility.ImageComperssion.Normal);

                        _requestService.AddAttachmentFurtherInformation(new AttachmentFurtherInformation
                        {
                            FurtherInformationId = furtherInformation.Id,
                            FurtherInformationType = FurtherInformationType.مامور_به_تحصیل_در_مقطع_دکتری_داخل_یا_خارج,
                            ImageName = Path.GetFileName(temppath)
                        });
                    }
                }
                if (typeOfPartTimeButEmployeesOtherUniversityUpload != null)
                {
                    foreach (var item in typeOfPartTimeButEmployeesOtherUniversityUpload)
                    {
                        string temppath = path + Guid.NewGuid().ToString() + Path.GetExtension(item.FileName);
                        item.InputStream.ResizeImageByWidth(500, temppath, Utility.ImageComperssion.Normal);

                        _requestService.AddAttachmentFurtherInformation(new AttachmentFurtherInformation
                        {
                            FurtherInformationId = furtherInformation.Id,
                            FurtherInformationType = FurtherInformationType.نوع_همکاری_نیمه_وقت_اما_به_صورت_تمام_وقت_شاغل_در_سایر_دانشگاهها_با_ارائه_حکم_کارگزینی_مبنی_بر_اعطای_پایه_سالیانه_دردانشگاه_دولتی,
                            ImageName = Path.GetFileName(temppath)
                        });
                    }
                }
                if (typeOfFullTimeButRetiredUpload != null)
                {
                    foreach (var item in typeOfFullTimeButRetiredUpload)
                    {
                        string temppath = path + Guid.NewGuid().ToString() + Path.GetExtension(item.FileName);
                        item.InputStream.ResizeImageByWidth(500, temppath, Utility.ImageComperssion.Normal);

                        _requestService.AddAttachmentFurtherInformation(new AttachmentFurtherInformation
                        {
                            FurtherInformationId = furtherInformation.Id,
                            FurtherInformationType = FurtherInformationType.نوع_همکاری_تمام_وقت_اما_بازنشسته_از_سایردانشگاههای_وابسته,
                            ImageName = Path.GetFileName(temppath)
                        });
                    }
                }
                if (typeOfFullTimeButNoRetired != null)
                {
                    foreach (var item in typeOfFullTimeButNoRetired)
                    {
                        string temppath = path + Guid.NewGuid().ToString() + Path.GetExtension(item.FileName);
                        item.InputStream.ResizeImageByWidth(500, temppath, Utility.ImageComperssion.Normal);

                        _requestService.AddAttachmentFurtherInformation(new AttachmentFurtherInformation
                        {
                            FurtherInformationId = furtherInformation.Id,
                            FurtherInformationType = FurtherInformationType.نوع_همکاری_تمام_وقت_اما_غیر_بازنشسته_در_صورت_استفاء,
                            ImageName = Path.GetFileName(temppath)
                        });
                    }
                }
                if (passPhDPassaUpload != null)
                {
                    foreach (var item in passPhDPassaUpload)
                    {
                        string temppath = path + Guid.NewGuid().ToString() + Path.GetExtension(item.FileName);
                        item.InputStream.ResizeImageByWidth(500, temppath, Utility.ImageComperssion.Normal);

                        _requestService.AddAttachmentFurtherInformation(new AttachmentFurtherInformation
                        {
                            FurtherInformationId = furtherInformation.Id,
                            FurtherInformationType = FurtherInformationType.گواهی_دوره_پسا_دکترا,
                            ImageName = Path.GetFileName(temppath)
                        });
                    }
                }
                if (takingSabbaticalUpload != null)
                {
                    foreach (var item in takingSabbaticalUpload)
                    {
                        string temppath = path + Guid.NewGuid().ToString() + Path.GetExtension(item.FileName);
                        item.InputStream.ResizeImageByWidth(500, temppath, Utility.ImageComperssion.Normal);

                        _requestService.AddAttachmentFurtherInformation(new AttachmentFurtherInformation
                        {
                            FurtherInformationId = furtherInformation.Id,
                            FurtherInformationType = FurtherInformationType.مجوز_سازمان_مرکزی_برای_فرصت_مطالعاتی,
                            ImageName = Path.GetFileName(temppath)
                        });
                    }
                }

                //--------------------------
                _unitOfWork.SaveChanges();
                return Json(new { Success = true,FurtherInformationId=furtherInformation.Id, Msg = "ثبت شد" });
            }
            return Json(new { Success = false, Msg = "خطا در ثبت!" });
        }

    }
}